/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');

/*
 *@todo  API21 标签列表
 */
exports.tagsList = function*(Env) {
  //var loginStatus = yield F.isLogin(Env);
  //var fields = Env.I;
  let fields = Env.I;
  let loginStatus = fields.loginStatus;

  var act = fields.act;//1 app端 11 web端
  var page = fields.page != undefined ? parseInt(fields.page) : 1;
  var pagesize = fields.pagesize != undefined ? parseInt(fields.pagesize) : C.pageSize;
  var beginIndex = (page - 1) * pagesize;//开始索引
  var type = fields.type;//标签组id类型 1普通标签 2 用户 3帖子 4lbs 5水印标签 6 美容标签 99 保留标签
  var manager = (fields.manager == 1 && F.isManager(loginStatus.groupid)) ? 1 : 0;  // 管理员为1 否则为0
  if (act == 1 || act == 11) {//取标签列表
    var addWhere = '';
    if (manager == 0) { // 非管理员
      addWhere = ' and tagcount>0';
    }

    var newFunction = 1;
    if (newFunction == 1) { // Todo 即将3月2x日上线功能 自定义发现页标签的管理
      if (manager == 0) {
        var tags = yield mysql.query('SELECT mt.tagid,mt.tagtype,mt.tagtitle,mt.tagimg,mt.tagcount,mt.pincount,mt.fix,mt.tagdesc FROM mh_tags mt ' +
          'JOIN mh_slider ms ON mt.tagid = ms.id WHERE ms.status=1 and ms.sstype=5 and ms.begintime<=UNIX_TIMESTAMP() and (ms.endtime+86400)>=UNIX_TIMESTAMP() ORDER BY sort limit ?,?',
          [beginIndex, pagesize]);
      }
      else {
        if (type != undefined) {
          type = parseInt(type);
          var tags = yield MTags.getTags("tagid,tagtype,tagtitle,tagimg,tagcount,pincount,fix,tagdesc",
            ' tagtype=?' + addWhere + ' ORDER BY tagcount desc limit ?,?', [type, beginIndex, pagesize]);//标签列表
        }
        else {
          var tags = yield MTags.getTags("tagid,tagtype,tagtitle,tagimg,tagcount,pincount,fix,tagdesc",
            ' (tagtype=1 or tagtype=3) ' + addWhere + ' ORDER BY tagcount desc limit ?,?', [beginIndex, pagesize]);//标签列表
        }
      }
    }
    else { // 之前功能
      if (type != undefined) {
        type = parseInt(type);
        var tags = yield MTags.getTags("tagid,tagtype,tagtitle,tagimg,tagcount,pincount,fix,tagdesc",
          ' tagtype=?' + addWhere + ' ORDER BY tagcount desc limit ?,?', [type, beginIndex, pagesize]);//标签列表
      }
      else {
        var tags = yield MTags.getTags("tagid,tagtype,tagtitle,tagimg,tagcount,pincount,fix,tagdesc",
          ' (tagtype=1 or tagtype=3) ' + addWhere + ' ORDER BY tagcount desc limit ?,?', [beginIndex, pagesize]);//标签列表
      }
    }

  }
  else if (act == 2 || act == 22) {//取某人订阅的标签列表
    var uid = fields.uid || loginStatus.uid;
    if (!uid) {
      return F.returnMsg(400, '请输入uid', 1);
    }
    // 用户是否存在
    var isUserExist = yield MUser.getUser('uid', 'uid=?', [uid]);
    if (isUserExist.length == 0) {
      return F.returnMsg(400, '用户不存在', 1);
    }
    var tags = yield mysql.query('SELECT mt.tagid,mt.tagtype,mt.tagtitle,mt.tagimg,mt.tagcount,mt.pincount,mp.* FROM mh_pintag mp INNER JOIN mh_tags mt ON mp.tagid=mt.tagid  WHERE mp.uid=? ORDER BY mp.timeline DESC LIMIT ?,?',
      [uid, beginIndex, pagesize]);
  }
  else if (act == 3 || act == 4 || act == 5) {//取某个标签信息（4 水印）
    var tagId = fields.tagid;
    if (tagId == undefined) {
      return F.returnMsg(400, '请输入标签id', 1);
    }
    var tags = yield F.returnTagInfo(parseInt(tagId), 1);
  }
  else if (act == 6) { // 最热门标签列表
    if (type != undefined) {
      type = parseInt(type);
      var tags = yield MTags.getTags("tagid,tagtype,tagtitle,tagimg,tagcount,pincount,fix,tagdesc",
        ' tagtype=? ORDER BY tagcount desc limit ?,?', [type, beginIndex, pagesize]);//标签列表
    }
    else {
      var tags = yield MTags.getTags("tagid,tagtype,tagtitle,tagimg,tagcount,pincount,fix,tagdesc",
        ' (tagtype=1 or tagtype=3) ORDER BY tagcount desc limit ?,?', [beginIndex, pagesize]);//标签列表
    }
  }

  if (tags.length == 0 || tags[0].tagid == undefined) {
    return F.returnMsg(300, '已没有数据了', 3);
  }
  for (var i in tags) {
    if (!loginStatus.status) {//未登录
      tags[i]['pin'] = false;
    }
    else {
      var pinTags = yield MTags.getPinTags("tagid", "uid=? and tagid=?", [loginStatus.uid, tags[i]['tagid']]);//查看是否订阅
      tags[i]['pin'] = pinTags.length > 0;
    }
    tags[i]['pincount'] = parseInt(tags[i]['pincount']) + C.appendParm.pinCount;
    tags[i]['tagurl'] = F.generateTagUrl(tags[i]['tagimg'], tags[i]['tagid']);
    if (act == 4) {//如果是水印标签 act=4 ，标签图用通栏图
      tags[i]['tagurl'] = F.generateTagBannerUrl(tags[i]['tagid']);
    }
    if (act == 5) {
      var poiid = fields.poiid;
      var pcode = '';
      var pname = '';
      var citycode = '';
      var cityname = '';
      var longitude = '';
      var latitude = '';
      var addressdetail = '';
      var poiDetail = yield  mysql.queryOne('SELECT version,poiid,pcode,pname,citycode,cityname,adcode,adname,address,`name`,longitude,latitude FROM mh_poi_detail WHERE version=? AND poiid=?',
        [C.amap.api_ver, poiid]);
      if (poiDetail) {
        pcode = poiDetail.pcode;
        pname = poiDetail.pname;
        citycode = poiDetail.citycode;
        cityname = poiDetail.cityname;
        longitude = poiDetail.longitude;
        latitude = poiDetail.latitude;
        addressdetail = poiDetail.adname + poiDetail.address + poiDetail.name;
      }
      else {
        F.AMAPSearchPoi([poiid],
          function (jsonData, pois) {
            var poisArr = jsonData.pois;
            mysql.query('insert into mh_poi_detail(version,poiid,pcode,pname,citycode,cityname,adcode,adname,address,`name`,longitude,latitude,poidetail,lasttid,tagid) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
              [C.amap.api_ver, pois.id, pois.pcode, pois.pname, pois.citycode, pois.cityname, pois.adcode, pois.adname,
                pois.address, pois.name, pois.longitude, pois.latitude, JSON.stringify(poisArr), 0, tags[i]['tagid']]);
            F.savePoi2Mongo({
              poiid: pois.id,
              name: pois.name,
              tagid: tagsid,
              longitude: pois.longitude,
              latitude: pois.latitude
            });
          }
        );
      }
      tags[i]['pcode'] = pcode;
      tags[i]['pname'] = pname;
      tags[i]['citycode'] = citycode;
      tags[i]['cityname'] = cityname;
      tags[i]['longitude'] = longitude;
      tags[i]['latitude'] = latitude;
      tags[i]['addressdetail'] = addressdetail;
    }
    tags[i]['tagmarkurl'] = '';
    if (tags[i]['tagtype'] == 3) {//水印标签
      if (!(manager && manager == 1 && F.isManager(loginStatus.groupid))) {
        delete tags[i]['fid'];//父id
        //delete tags[i]['fix'];//是否固定
        if (act == 2 || act == 3 || act == 5) {
          tags[i].tagtype = 1;
        }
      }
      else {

      }
      tags[i]['tagmarkurl'] = F.generateTagMarkUrl(tags[i]['tagid']);
      tags[i]['tagbannerurl'] = F.generateTagBannerUrl(tags[i]['tagid']);
    }

    if (act == 5) {
      tags[i].tagtype = 4; //LBS标签
    }


    delete tags[i]['tagimg'];
    if (act == 3 || act == 4 || act == 5) {//取得具体标签信息
      var pinUsers = JSON.parse(tags[i].pinusers);
      for (var j in pinUsers) {
        pinUsers[j].faceUrl = F.generateFaceUrl(pinUsers[j].face, pinUsers[j].uid);
        delete pinUsers[j].face;
      }
      tags[i].pinusers = pinUsers;
      /*2016-01-07
      ////////取得某标签的子标签开始
      var childTags = yield mysql.query('SELECT tagid,tagtitle,tagimg FROM mh_tags WHERE fid=?', [tagId]);
      for (var j in childTags) {
        childTags[j]['tagurl'] = F.generateTagUrl(childTags[j]['tagimg'], childTags[j]['tagid']);
        delete childTags[j].tagimg;
      }
      tags[i].chdtags = childTags;
      ////////取得某标签的子标签结束
      */
      if (loginStatus.status) {//已登录，写标签浏览记录
        mysql.query('INSERT INTO mh_tag_viewlog(uid,timeline,tagid) VALUES(?,UNIX_TIMESTAMP(),?)',
          [parseInt(loginStatus.uid), tagId]);
        var tagData = yield  F.returnTagInfo(tagId, 1);
        mysql.query('INSERT INTO mh_user_tagcount(uid,tagid,tagcount,timeline) VALUES(?,?,?,UNIX_TIMESTAMP()) ON DUPLICATE KEY UPDATE tagcount=?,timeline=UNIX_TIMESTAMP()',
          [parseInt(loginStatus.uid), tagId, tagData[0].tagcount, tagData[0].tagcount]);
      }
    }
  }
  return F.returnMsg(200, '标签返回成功', 3, {pageIndex: page, items: tags});
};
